# -*- coding: utf-8 -*-

import json
from public_util.util.AutoUrl import Route
from django.http import HttpResponse, Http404
from django.shortcuts import render_to_response
from package.models import Branch, Project, Task, Handle
from django.core.exceptions import ObjectDoesNotExist


@Route()
def branch(request):
    """分支CRUD接口"""
    if request.method == "GET":
        state_type = Branch.STATE_TYPE
        req = request.REQUEST.get
        init = req("init", 0)
        if init:
            pro_objs = Project.filter_project(request)
            return render_to_response("branch/branch_index.html", locals())
        else:
            branch_objs = Branch.filter_record(request)
            item_list = []
            for obj in branch_objs:
                try:
                    prev_branch_name = obj.prev_branch.branch_name
                except ObjectDoesNotExist:
                    prev_branch_name = "无"
                item_list.append([obj.project.pro_name, obj.branch_name, prev_branch_name,
                                  obj.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                                  obj.state, obj.id])
            return HttpResponse(json.dumps({"aaData": item_list}), content_type="application/json")
    elif request.method == "POST":
        err_msg = ""
        params = request.post_dic
        params["project"] = Project.objects.filter(id=params.get("project", 0)).first()
        params["prev_branch"] = Branch.objects.filter(id=params.get("prev_branch", 0)).first()
        p_id = request.GET.get("id", 0)
        if p_id:
            try:
                Branch.objects.filter(id=p_id).update(**params)
            except Exception as e:
                err_msg = e
        else:
            try:
                Branch(**params).save()
            except Exception as e:
                err_msg = e
    elif request.method == "PUT":
        err_msg = ""
        params = request.get_dic
        b_id = params.pop("id")
        b_objs = Branch.objects.filter(id=b_id)
        try:
            if int(params.get("state", 0) or 0) == 1:
                Handle.create_handle(
                    user_id=request.admin.id,
                    user=request.admin.alias,
                    ope_id=9,
                    pro_name=b_objs.first().project.pro_name,
                    branch_name=b_objs.first().branch_name
                )
            b_objs.update(**params)
        except Exception as e:
            err_msg = e
        return render_to_response("feedback.html", locals())


@Route()
def branch_detail(request):
    """分支详情页面接口"""
    state_type = Branch.STATE_TYPE
    pro_tuple = Project.filter_project(request).values_list("id", "pro_name")
    branch_objs = Branch.filter_project(request)
    p_id = request.REQUEST.get("id", 0)
    if p_id:
        model = branch_objs.filter(id=p_id).first()
        branch_objs = branch_objs.exclude(id=p_id)
    bra_tuple = branch_objs.values_list("id", "branch_name")
    return render_to_response("branch/branch_detail.html", locals())
